import React, { useEffect, useState } from 'react'
import useGetTableDataNoPagination from '@/hooks/useGetTableDataNoPagination'
import { queryExpandSkuDetail } from '@/api/task'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useReorderColumns, useViewColumns } from '../columns'
import { ReorderExpandListVO, ReorderExpandDetailVO } from '../types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import weekOfYear from 'dayjs/plugin/weekOfYear'
import { Empty, Modal, Table } from 'antd'
import { onValuesChange } from '@/utils/onValuesChange'
import { getProductClassConfigByType, getSpuOptions } from '@/api/goods'
dayjs.extend(weekOfYear)
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [isView, setisView] = useState(false)
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [viewList, setviewList] = useState<ReorderExpandDetailVO[]>([])
  const [form] = useForm()
  const navigate = useNavigate()
  const { tableProps, params, search, reset } = useGetTableDataNoPagination<ReorderExpandListVO>(queryExpandSkuDetail, {
    form: form,
    immediatelySend: false,
  })
  useEffect(() => {
    getProductClassConfig()
  }, [])
  const onView = (info: ReorderExpandListVO) => {
    setisView(true)
    setviewList(info?.subList || [])
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.className,
        }
      }) || []
    setclassBig(classIdOptions)
    form.setFieldsValue({
      weekNum: dayjs(),
      largeClassName: classIdOptions?.[0]?.value || null,
    })
    search({
      weekNum: dayjs().week(),
      largeClassName: classIdOptions?.[0]?.value || null,
    })
  }
  const onCancel = () => {
    setisView(false)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  return (
    <PageContainer className="suppliermgr_page">
      <SearchForm
        className="task_reorder_wrap"
        params={null}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['skuCode'], form)}
        searchConfig={[
          {
            label: '计算周',
            name: 'weekNum',
            type: 'DatePicker',
            config: {
              picker: 'week',
              maxDate: dayjs().subtract(1, 'week'),
            },
            rules: [{ required: true, message: '请选择计算周' }],
          },
          {
            label: '大类',
            name: 'largeClassName',
            type: 'Select',
            option: classBig,
            rules: [{ required: true, message: '请选择大类' }],
          },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCode',
            placeholder: '商品条码',
            type: 'Input',
          },
        ]}
        onFinish={(vals: any) => {
          search({
            ...vals,
            weekNum: dayjs(vals.weekNum).week(),
          })
        }}
        onReset={() => {
          form.setFieldsValue({
            weekNum: dayjs(),
            largeClassName: classBig?.[0]?.value || null,
            spuCode: null,
            skuCode: null,
          })
          search({
            current: 1,
            size: 10,
            weekNum: dayjs().week(),
            largeClassName: classBig?.[0]?.value || null,
            spuCode: null,
            skuCode: null,
          })
        }}
      ></SearchForm>
      <CustomTable
        bordered
        columns={useReorderColumns({ onView })}
        {...tableProps}
        rowKey={(row) => row.taskId}
        isScrollY
        filterDomClassName="task_reorder_wrap"
        extraHeight={30}
      />
      <Modal width={2000} title="导入明细" maskClosable open={isView} onCancel={onCancel} footer={null}>
        <div className="header_table_style small_sise_customtable">
          <Table
            className="reorder_view_table_wrap"
            bordered
            pagination={false}
            scroll={{
              x: 1000,
            }}
            columns={useViewColumns()}
            dataSource={viewList}
            rowKey={(rows) => rows.skuCode}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          ></Table>
        </div>
      </Modal>
    </PageContainer>
  )
}

export default Index
